<template>
  <div class="container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索 -->
        <el-form :model="requestParameters" ref="requestParameters">
          <div class="filter-container">
            <el-row :gutter="15">
              <el-col :span="4">
                <el-form-item label="关键字" prop="keyword">
                  <el-input
                    @keyup.enter="handleFilter"
                    style="width: 180px"
                    placeholder="根据文章标题搜索"
                    class="filter-item"
                    v-model="requestParameters.keyword"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="状态：" prop="state">
                  <el-select
                    class="filter-item"
                    style="width: 100px"
                    v-model="requestParameters.state"
                    @click="handleFilter"
                  >
                    <el-option
                      v-for="item in status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="1">
                <el-button size="small" type="primary" @click="crea"
                  >清除</el-button
                >
              </el-col>
              <el-col :span="1">
                <el-button
                  class="filter-item"
                  size="small"
                  type="primary"
                  @click="handleFilter"
                  >搜索</el-button
                >
              </el-col>
              <el-col :span="14">
                <el-button
                  class="filter-item fr"
                  size="small"
                  style="margin-left: 10px"
                  @click="handleChange('add')"
                  type="success"
                  icon="el-icon-edit"
                  >新增技巧</el-button
                >
              </el-col>
            </el-row>
          </div>
        </el-form>
        <!-- 数据记录 -->
        <el-alert
          v-if="alertText !== ''"
          :title="alertText"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>
        <!-- end -->
        <!-- 数据列表 -->
        <el-table
          :key="tableKey"
          :data="dataList"
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="index" align="left" label="序号" width="80px">
          </el-table-column>
          <el-table-column align="left" label="文章标题">
            <template slot-scope="scope">
              <span>{{ scope.row.title }}</span>
              <a
                v-show="scope.row.videoURL"
                class="el-icon-film"
                @click.prevent="open(scope.row)"
              ></a>
            </template>
          </el-table-column>
          <el-table-column align="left" label="阅读数">
            <template slot-scope="scope">
              <span>{{ scope.row.visits }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="录入人">
            <template slot-scope="scope">
              <span>{{ scope.row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="录入时间">
            <template slot-scope="scope">
              <span>{{
                scope.row.createTime
                  | parseTimeByString("{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="left" label="状态">
            <template slot-scope="scope">
              <span v-if="scope.row.state == 1">已启用</span>
              <span v-else>已禁用</span>
            </template>
          </el-table-column>
          <!-- 操作按钮 -->
          <el-table-column
            align="left"
            label="操作"
            width="280"
            class-name="small-padding fixed-width"
            class="czTable"
          >
            <template slot-scope="scope">
              <el-button type="text" @click="preve(scope.row.id)"
                >预览</el-button
              >
              <el-button type="text" @click="handleStatus(scope.row)">
                <span v-if="scope.row.state == 0">启用</span>
                <span v-else>禁用</span>
              </el-button>

              <el-button
                v-show="scope.row.state === 1"
                type="text"
                @click="handleChange(scope.row.id)"
                >修改</el-button
              >

              <el-button
                v-show="scope.row.state === 1"
                v-if="scope.row.status != 'deleted'"
                type="text"
                @click="removeUser(scope.row.id)"
                >删除</el-button
              >
              <el-button v-show="scope.row.state === 0" type="text" disabled
                >修改</el-button
              >

              <el-button v-show="scope.row.state === 0" type="text" disabled
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- end -->
        <!-- 分页 -->
        <div class="pagination">
          <div class="pages">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="Number(requestParameters.page)"
              :total="Number(total)"
              :page-size="Number(requestParameters.pagesize)"
              :page-sizes="[10, 20, 30, 50]"
              layout="sizes, prev, pager, next, jumper"
            ></el-pagination>
          </div>
        </div>
        <!-- end -->
        <!-- 新增标签弹层 -->
        <Dialog
          ref="editUser"
          :titleInfo="titleInfo"
          :formBase="formData"
          v-on:newDataes="getList"
        ></Dialog>
        <Preview
          ref="preview"
          :titleInfo="titleInfo"
          :formPre="formData"
          v-on:newDataes="getList"
        ></Preview>
      </el-card>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      width="46%"
      :before-close="handleClose"
    >
      <video
        ref="video"
        :src="videoURL"
        style="width: 100%"
        loop
        controls
      ></video>
    </el-dialog>
  </div>
</template>

<script>
import { status } from '@/api/hmmm/constants'
import { list, remove, detail, changeState } from '@/api/hmmm/articles'
import Dialog from './../components/articles-add'
import Preview from './../components/articles-preview'
export default {
  name: 'ArticlesList',
  components: {
    Dialog,
    Preview
  },
  data () {
    return {
      dialogVisible: false,
      videoURL: '',
      disabled: null,
      tableKey: 0,
      dataList: [],
      total: null,
      listLoading: true,
      alertText: '',
      requestParameters: {
        keyword: '',
        state: ''
      },
      page: 1,
      pagesize: 10,
      titleInfo: {
        pageTitle: '文章', // 页面标题
        text: '' // 新增、编辑文本
      },
      formData: {
        title: '',
        visits: '',
        username: '',
        state: ''
      }
    }
  },
  computed: {
    status () {
      return status
    }
  },
  methods: {
    // 初始数据
    initialDate () {
      // 读取数据
      this.getList()
    },
    // 获取列表数据
    async getList (params) {
      this.listLoading = true
      const data = {
        page: this.page,
        pagesize: this.pagesize,
        keyword: this.requestParameters.keyword,
        state: this.requestParameters.state.toString() || null
      }
      const { data: res } = await list(data)

      // 获取数据给dataList
      this.dataList = res.items
      // 获取总条数
      this.total = res.counts
      this.alertText = `数据一共 ${this.total} 条记录`
      this.listLoading = false
    },
    // 清除
    crea () {
      this.requestParameters.keyword = ''
      this.requestParameters.state = ''
    },
    // 搜索信息
    async handleFilter () {
      this.requestParameters.page = 1

      // this.parameters.keyword = 0
      this.getList(this.requestParameters)
      this.$refs.requestParameters.resetFields()
    },
    // 每页显示信息条数
    handleSizeChange (val) {
      this.requestParameters.pagesize = val
      if (this.requestParameters.page === 1) {
        this.getList(this.requestParameters)
      }
    },
    // 进入某一页
    handleCurrentChange (val) {
      this.page = val
      this.getList()
    },
    // 打开弹窗视频
    open (row) {
      this.dialogVisible = true
      this.videoURL = row.videoURL
      this.$nextTick(() => {
        this.$refs.video.play()
      })
    },
    // 关闭弹窗视频
    handleClose (done) {
      this.dialogVisible = false
      this.$refs.video.pause()
    },

    // **********************************
    // 搜索的项目
    // 添加、编辑之后表单清空
    query () {
      this.formData = {}
    },
    // 新增文章、编辑文章
    handleChange (id) {
      this.query()
      this.$refs.editUser.dialogFormV()
      if (id === 'add') {
        this.titleInfo.text = '新增' // 给弹层传参
      } else {
        this.titleInfo.text = '修改' // 给弹层传参
        this.hanldeEditForm(id)
      }
    },
    preve (id) {
      this.$refs.preview.dialogFormDd()
      this.titleInfo.text = '预览'
      this.hanldeEditForm(id)
    },
    // 窗口操作**********************************
    // 编辑
    // 表单详情数据加载
    async hanldeEditForm (objeditId) {
      this.formData.id = objeditId
      const { data: res } = await detail({ id: objeditId })
      // 获取详情 给formData
      this.formData = res
      if (res.creatorID === 2) {
        this.formData.username = '超级管理员'
      }
    },
    // 删除
    removeUser (user) {
      this.$confirm('此操作将永久删除文章 ' + ', 是否继续?', '提示', {
        type: 'warning'
      })
        .then(async () => {
          await remove({ id: user })
            .then(response => {
              this.$message.success('成功删除了文章' + '!')
              this.dataList.splice(user, 1)
              this.getList(this.requestParameters)
            })
            .catch(response => {
              this.$message.error('删除失败!')
            })
        })
        .catch(() => {
          this.$message.info('已取消操作!')
        })
    },

    // 启用、禁用
    async handleStatus (val) {
      val.state === 1 ? val.state = 0 : val.state = 1

      const param = {
        id: val.id,
        state: val.state
      }
      try {
        await changeState(param)
        this.$message.success('修改状态成功！')
      } catch (error) {
        console.warn(error)
        this.$message.error('修改状态失败！')
        val.state === 1 ? val.state = 0 : val.state = 1
      }
    }
  },
  // 挂载结束
  mounted: function () { },
  // 创建完毕状态
  created () {
    var _this = this
    this.initialDate()
    // 键盘enter操作
    document.onkeydown = function (e) {
      var key = window.event.keyCode
      if (key === 13) {
        _this.handleFilter(this.requestParameters)
      }
    }
  },
  // 组件更新
  updated: function () { }
}
</script>

<style scoped lang='less'>
.app-container {
  .alert {
    margin-top: -5px;
    margin-bottom: 15px;
  }
  .czTable {
    font-size: 14px;
  }
  .pagination {
    background-color: #fff;
    margin-top: 10px;
    text-align: right;
  }
}
/deep/ .el-dialog__header {
  height: 50px;
}
</style>
